package com.cabinet.base.entity;

import java.util.Date;

import javax.persistence.PrePersist;
import javax.persistence.PreRemove;
import javax.persistence.PreUpdate;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 实体操作监听
 * 
 * @author nibili 2015年12月22日
 * 
 */
public class BaseEntityListener {

    /** The logger. */
    private static Logger logger = LoggerFactory.getLogger(BaseEntityListener.class);

    /**
     * Pre persist.
     * 
     * @param object
     *            the object
     */
    @PrePersist
    public void prePersist(Object object) {

        if (object instanceof IdEntity) {
            IdEntity baseEntity = (IdEntity) object;
            Date date = java.util.Calendar.getInstance().getTime();
            if (baseEntity.getAddTime() == null) {
                // 创建新对象
                baseEntity.setAddTime(date);
            }
            if (baseEntity.getLastModifyTime() == null) {
                baseEntity.setLastModifyTime(date);
            }
            // baseEntity.setCreateBy(loginName);
        }
    }

    /**
     * Pre update.
     * 
     * @param object
     *            the object
     */
    @PreUpdate
    public void preUpdate(Object object) {

        if (object instanceof IdEntity) {
            IdEntity baseEntity = (IdEntity) object;
            Date date = java.util.Calendar.getInstance().getTime();
            // 修改旧对象
            baseEntity.setLastModifyTime(date);
            // baseEntity.setLastModifyBy(loginName);
            logger.info("{}对象(ID:{}) 被 {} 在 {} 修改", new Object[] { object.getClass().getName(), baseEntity.getId(), null, new Date() });
        }
    }

    /**
     * Pre update.
     * 
     * @param object
     *            the object
     */
    @PreRemove
    public void preRemove(Object object) {

        if (object instanceof IdEntity) {
            IdEntity baseEntity = (IdEntity) object;
            Date date = java.util.Calendar.getInstance().getTime();
            // 修改旧对象
            baseEntity.setLastModifyTime(date);
            // baseEntity.setLastModifyBy(loginName);
            logger.info("{}对象(ID:{}) 被 {} 在 {} 删除", new Object[] { object.getClass().getName(), baseEntity.getId(), null, new Date() });
        }
    }
}
